package com.cyx.netty.c1;

import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class TestByteBuffer {
    public static void main(String[] args) {
        // FileChannel
        // 1.输入输出流 2.RandomAccessFile
        try {
            File file = ResourceUtils.getFile("classpath:data.txt");
            FileChannel channel = new FileInputStream(file).getChannel();
            // 准备缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(10);
            while (true) {
                // 读取数据
                int len = channel.read(buffer);
                if (len == -1) {
                    break;
                }
                // 打印buffer内容
                buffer.flip(); // 切换至读模式
                while (buffer.hasRemaining()) { // 是否还有剩余数据
                    byte b = buffer.get();
                    System.out.println((char) b);
                }
                buffer.clear(); // 切换为写模式

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
